package com.idc.quotation.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.idc.common.cache.LimitResult;
import com.idc.common.cache.LimitUtil;
import com.idc.common.mvc.vo.ResponseVo;
import com.idc.common.util.LogUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author bing
 */
@Aspect
@Component
@Slf4j
public class RedisLuaAspect {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private LimitUtil limitUtil;

	@Pointcut("@annotation(com.eetruts.common.cache.annotation.RedisLimit)")
	public void limitPoint() {
	}

	@Around("limitPoint()")
	public Object interceptor(ProceedingJoinPoint pjp) {
		Object result = null;
		try {
			LimitResult limitResult = limitUtil.requestLimit(stringRedisTemplate, pjp);
			if (!limitResult.isSuccess()) {
				return ResponseVo.fail(limitResult.getCode(), limitResult.getMessage());
			}
			result = pjp.proceed();
		} catch (Throwable e) {
			LogUtil.error(log, "limit error", e);
		} finally {
			limitUtil.clearKey();
		}
		return result;
	}

}
